<template>
	<scroll-view scroll-y="true" class="shoppingCart">
		<view class="main"  v-if="info.length > 0">
			<view class="top">
				<view class="left">
					<!-- <image src="https://hdsq.aoorange.cn/attachment/xcx/store/car_icon.png" mode="widthFix"></image> -->
					<text></text>
				</view>
				<view class="right" @click="getedit()">
					<image :src="'https://hdsq.aoorange.cn/attachment/xcx/icon/bianji.png'" mode="aspectFill"></image>
					<text>{{isedit?'完成':'编辑'}}</text>
				</view>
			</view>
			
            <view class="content" v-for="(store,index) in info" :key="index">
				<view class="contop">
					<view :class="selStore[index]?'sel':'nosel'" @click="selStoreFun(index)"></view>
					<image :src="store.merchant_icon" mode="widthFix"></image>
					<text @click="jump('store_home', store.merchant_id)">{{store.merchant_name}}</text>
				</view>
				<view class="coupon" v-if="false">
					已用优惠券：满<text>100</text>减<text>10</text>元 >           
				</view>
				<uni-swipe-action v-for="(item,index1) in store.productList" :key="index1">
					
					<uni-swipe-action-item :options="options" @click="delItem(item.id)" @change="change">
						<view class='cont'>
							<view class="left">
								<view :class="selList[item.id]?'sel':'nosel'" @click="selProduct(item.id, index)"></view>
								<image :src="item.product_img" mode="aspectFill" @click="jump('product_view', 'id='+item.product_id+'&merchantId='+store.merchant_id)"></image>
							</view>
							<view class="right">
								<text class="right-p" @click="jump('product_view', 'id='+item.product_id+'&merchantId='+store.merchant_id)">
									<text v-if="item.reductionName != ''" class="state" style="background:rgba(235, 89, 56, 1);">{{item.reductionName}}{{item.isReduction == 1 ? '满减' : ''}}</text>
									{{item.product_name}}
								</text>
								<text @click="jump('product_view', 'id='+item.product_id+'&merchantId='+store.merchant_id)">{{item.sku_name}}</text>
								<text class="price" @click="jump('product_view', 'id='+item.product_id+'&merchantId='+store.merchant_id)">{{item.price > 0 ? '￥'+item.price : ''}}{{item.price > 0 && item.point_exchange > 0 ? ' + ' : ''}}{{item.point_exchange > 0 ? item.point_exchange+'运动币' : ''}}</text>
								<text class="oneline" v-if="item.market_price > 0">{{item.market_price}}</text>
								<view class="uni-numbox">
									<view class="uni-numbox-minus" :class="cartNumList[item.id].disableSubtract ? '' : 'uni-numbox-disabled'" @click="_calcValue('subtract', item.id)">-</view>  
									<input class="uni-numbox-value" type="number" :value="cartNumList[item.id].number" @blur="_onBlur" disabled="disabled" :data-id="item.id">  
									<view class="uni-numbox-plus" :class="cartNumList[item.id].disableAdd ? '' : 'uni-numbox-disabled'" @click="_calcValue('add', item.id)">+</view>
								</view>  
							</view>
						</view>
					</uni-swipe-action-item>
				</uni-swipe-action>
				
			</view>
			<view class="bottom">
				<view class="left">
					<view :class="allsel?'sel':'nosel'" @click="allSelFun()"></view>
					<text>全选</text>
				</view>
				<view class="right">
					<view v-if="isedit" class="del" @click="delAll()">
						删除
					</view>
					<view v-if="!isedit" class="text">
						<view class="all">
							<text>合计</text>
							<text>{{selTotalMoney == 0 && selTotalPoint == 0 ? '0' : ''}}{{selTotalMoney > 0 ? '￥'+selTotalMoney : ''}}{{selTotalMoney > 0 && selTotalPoint > 0 ? ' + ' : ''}}{{selTotalPoint > 0 ? selTotalPoint+'运动币' : ''}}</text>
						</view>
						<view class="freight">不含运费</view>
					</view>
					<text v-if="!isedit" class="pay" @click="confirmOrder()">结算({{selTotalNum}})</text>
				</view>
			</view>

		</view>
		<view v-if="info.length == 0" class="noshoppingCart">
			<image :src="'https://hdsq.aoorange.cn/attachment/xcx/icon/nocar.png'" mode="aspectFill"></image>
			<text>
				暂未有商品加入购物车～
			</text>
		</view>
	</scroll-view>

</template>

<script>
	import serve from '../../static/request.js';
	import storage from '../../static/appkey.js';
	import common from '../../static/jump.js';
	export default {
		data() {
			return {
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#EB5938',
						color: "#ffffff"
					}
				}],
				list: [{},{},{},{}],
				allsel: false,
				isedit: false,
				
				info: {},
				cartNumList: [],
				selStore: [],
				selList: [],
				selTotalNum: 0,
				selTotalMoney : 0,
				selTotalPoint : 0,
			}
		},
		methods: {
			delItem(cartId) {
				var self = this;
				let sku_id = self.cartNumList[cartId].sku_id;
				uni.showModal({
				    title: '提示',
				    content: '您确定删除该产品吗',
				    success: function (res) {
				        if (res.confirm) {
				            serve.request({
								url: '/shop/cart-item/delete-ids',
								data:{
									appkey: uni.getStorageSync('appkey'),
									'access-token': uni.getStorageSync('access-token'),
									'sku_ids':sku_id,
									type : 1,
								}
							}).then(res => {
								uni.showToast({
									title:res.message,
								});
								if(res.code == 200) {
									let storeKey = self.cartNumList[cartId].store_key;
									let cartKey = self.cartNumList[cartId].cart_key;
									if(self.info[storeKey].productList.length == 1) {
										self.info.splice(storeKey, 1);
									} else {
										self.info[storeKey].productList.splice(cartKey, 1);
									}
									self.cartNumList[cartId] = [];
									self.$forceUpdate();
									self.totalSelFun();
								} 
							});
				        } 
				    }
				});
			},
			delAll(){
				var self = this;
				if(self.selTotalNum == 0) {
					uni.showToast({
						title: "请选择要删除的产品",
						icon: 'none'
					});
					return ;
				}
				let skuIds = '';
				let delSkuId = [];
				self.info.forEach((storeItem, key)=> {
					storeItem.productList.forEach((item,key) => {
						if(self.selList[item.id]) {
							skuIds += item.sku_id + ',';
							delSkuId[item.id] = item.id;
						} 
					});
				});
				uni.showModal({
				    title: '提示',
				    content: '您确定删除选择的产品吗',
				    success: function (res) {
				        if (res.confirm) {
				            serve.request({
								url: '/shop/cart-item/delete-ids',
								data:{
									appkey: uni.getStorageSync('appkey'),
									'access-token': uni.getStorageSync('access-token'),
									'sku_ids':skuIds,
									type : 1,
								}
							}).then(res => {
								uni.showToast({
									title:res.message,
								});
								if(res.code == 200) {
									delSkuId.forEach((cartId, key) => {
										let storeKey = self.cartNumList[cartId].store_key;
										let cartKey = self.cartNumList[cartId].cart_key;
										if(self.info[storeKey].productList.length == 1) {
											self.info.splice(storeKey, 1);
										} else {
											self.info[storeKey].productList.splice(cartKey, 1);
										}
										self.cartNumList[cartId] = [];
									});
									self.$forceUpdate();
									self.totalSelFun();
								} 
							});
				        } 
				    }
				});
			},
			confirmOrder() {
				var self = this;
				if(self.selTotalNum == 0) {
					uni.showToast({
						title: "请选择要提交的产品",
						icon: 'none'
					});
					return ;
				}
				let cartIds = '';
				self.info.forEach((storeItem, key)=> {
					storeItem.productList.forEach((item,key) => {
						if(self.selList[item.id]) {
							cartIds += item.id + ',';
						} 
					});
				});
				self.jump('addOrder', 'type=cart&data='+cartIds);
			},
			change(open) {
				console.log('当前开启状态：' + open)
			},
			selStoreFun(index) {
				let state = true;
				if(this.selStore[index]) {
					this.selStore[index] = false;
					state = false;
				} else {
					this.selStore[index] = true;
				}
				let productList = this.info[index].productList;
				productList.forEach((item, index) => {
					this.selList[item.id] = state;
				});
				this.$forceUpdate();
				this.totalSelFun();
			},
			selProduct(cartId, index) {
				if(this.selList[cartId]) {
					this.selList[cartId] = false;
				} else {
					this.selList[cartId] = true;
				}
				let state = false;
				let productList = this.info[index].productList;
				productList.forEach((item, index) => {
					if(this.selList[item.id]){
						state = true;
					}
				});
				this.selStore[index] = state;
				this.$forceUpdate();
				this.totalSelFun();
			},
			allSelFun() {
                
                this.info.forEach((storeItem, key)=> {
                	this.selStore[key] = this.allsel ? false : true;
                	storeItem.productList.forEach((item,key) => {
                		this.selList[item.id] = this.allsel ? false : true;
                	})
                });
                this.allsel = !this.allsel;
				// if(this.allsel) {
				// 	this.selList = [];
				// 	this.selStore = [];;
    //                 });
				// 	this.allsel = false;
				// } else {
				// 	this.info.forEach((storeItem, key)=> {
				// 		this.selStore[key] = true;
				// 		storeItem.productList.forEach((item,key) => {
				// 			this.selList[item.id] = true;
				// 		});
				// 	});
				// 	this.allsel = true;
				// }
				this.$forceUpdate();
				this.totalSelFun();
			},
			totalSelFun() {
				let isAllSel = true;
				let totalMoney = 0;
				let totalPoint = 0;
				let totalNum = 0;
				this.info.forEach((storeItem, key)=> {
					storeItem.productList.forEach((item,key) => {
						if(this.selList[item.id]) {
							totalNum ++;
							let productNum = this.cartNumList[item.id].number;
							totalMoney = parseFloat(Number(totalMoney) + Number(productNum * item.price));
							totalPoint = parseFloat(Number(totalPoint) + Number(productNum * item.point_exchange));
						} else {
							isAllSel = false;
						}
					});
				});
				this.allsel = isAllSel;
				this.selTotalMoney = parseFloat(totalMoney).toFixed(2);
				this.selTotalPoint = totalPoint;
				this.selTotalNum = totalNum;
				this.$forceUpdate();
			},
			getedit() {
				this.isedit = !this.isedit
			},
			
			_calcValue(type, cartId) {
				let cartNumItem = this.cartNumList[cartId];
				let merchantId = cartNumItem.merchantId;
				let value = cartNumItem.number;  
				let step = cartNumItem.min;  
				let min = cartNumItem.min;
				let max = cartNumItem.max;
				let sku_id = cartNumItem.sku_id;
				if (type === 'subtract') {  
					value -= step  
				} else if (type === 'add') {  
					value = parseInt(Number(value) + Number(step))
				}  
				if(value > max) {
					uni.showToast({
						title: "当前产品最大购买数量为："+max,
						icon : 'none',
					});
					return ;
				}
				if (value < min) {  
					this.delItem(cartId);
					return ;
				}  
				if(value == min) {
					this.cartNumList[cartId].disableSubtract = false;
				}
				if(value == max) {
					this.cartNumList[cartId].disableAdd = false;
				}
				serve.request({
					url: '/shop/cart-item/add-or-edit',
					data: {
						appkey: uni.getStorageSync('appkey'),
						'access-token': uni.getStorageSync('access-token'),
						'sku_id': sku_id,
						num: value,
						type: 1,
						merchantId: merchantId,
					}
				}).then(res => {
					uni.showToast({
						title: res.message,
						icon : 'none'
					});
					if(res.code == 200) {
						// this.$set(this.cartNumList[cartId], 'number', value);
						this.cartNumList[cartId].number = value;
						this.$forceUpdate();
						console.log(1);
						this.totalSelFun();
					}
				});
			},
			_onBlur(event) {
				const cartId = event.target.dataset.id;
				let value = event.detail.value;
				let cartNumItem = this.cartNumList[cartId];
				let merchantId = cartNumItem.merchantId;
				let nowNum = cartNumItem.number;
				let min = cartNumItem.min;
				let max = cartNumItem.max;
				let sku_id = cartNumItem.sku_id;
				if (!value) {
					this.$forceUpdate();
					return  
				}  
				value = +value;
				if (value > max) {
					var self = this;
					uni.showToast({
						title: "当前产品最大购买数量为："+max,
						icon : 'none',
					});
					this.cartNumList[cartId].number = Number(nowNum);
					this.$forceUpdate();
					return ;
					// value = max;  
				} else if (value < min) { 
					uni.showToast({
						title: "当前产品最少购买数量为："+min,
						icon : 'none'
					});
					this.cartNumList[cartId].number = Number(nowNum);
					this.$forceUpdate();
					return ;
					// value = min  
				}  
				if(value == min) {
					this.cartNumList[cartId].disableSubtract = false;
				}
				if(value == max) {
					this.cartNumList[cartId].disableAdd = false;
				}
				serve
					.request({
						url: '/shop/cart-item/add-or-edit',
						data: {
							appkey: uni.getStorageSync('appkey'),
							'access-token': uni.getStorageSync('access-token'),
							'sku_id': sku_id,
							num: value,
							type: 1,
							merchantId : merchantId,
						}
					})
					.then(res => {
						uni.showToast({
							title: res.message,
							icon : 'none'
						});
						if(res.code == 200) {
							this.cartNumList[cartId].number = Number(value);
							this.$forceUpdate();
						}
					});
				
			},
			getInfo() {
				serve.request({
					url: '/shop/cart-item/index',
					data: {
						appkey: uni.getStorageSync('appkey'),
						'access-token': uni.getStorageSync('access-token'),
					}
				}).then(res => {
					this.info = res.data;
					if(this.info.length > 0) {
						this.info.forEach((item, key) => {
							item.productList.forEach((cartItem, cartrKey) => {
								this.cartNumList[cartItem.id] = {
									'merchantId': item.merchant_id,
									'store_key' : key,
									'cart_key' : cartrKey,
									'sku_id' : cartItem.sku_id,
									'number' : cartItem.number,
									'disableSubtract': (cartItem.number == cartItem.min_buy ? true : false),
									'min' : cartItem.min_buy,
									'max' : cartItem.sku_stock,
									'step': cartItem.min_buy,
									'disableAdd': (cartItem.number == cartItem.sku_stock ? true : false),
								};
							});
						});
					}
				});
			},
			jump(jump_type, jump_link){
				common.jump(jump_type, jump_link);
			},
		},
		onLoad() {
			if(uni.getStorageSync('access-token') == '') {
				common.jump('login');
				return ;
			}
			
		},
		onShow() {
			this.getInfo();
		},
		onPullDownRefresh() {
			console.log('refresh');
			this.getInfo();
		}
	}
</script>

<style scoped lang="scss">
	@media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
		    .main {
		        padding-bottom: 224rpx !important;
				.bottom{
					 padding-bottom: 12px !important;
				}
		    }
		}
	.shoppingCart {
		max-height: 100vh;
        .noshoppingCart{
			width: 100%;
			min-height: 80vh;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			image{
				width: 128rpx;
				height: 116rpx;
			}
			text{
				font-size:28rpx;
				color:rgba(204,204,204,1);
				margin-top: 38rpx;
			};
		}
		.main {
			width: 100%;
			padding-bottom: 200rpx;

			.top {
				display: flex;
				padding: 33rpx 30rpx;
				box-sizing: border-box;
				justify-content: space-between;
				align-items: center;
				color: #666666;
				border-bottom: 1rpx rgba(235, 236, 240, 1) solid;

				.left {
					font-size: 32rpx;
					display: flex;
					align-items: center;

					image {
						width: 35rpx;
						height: 33rpx;
						margin-right: 13rpx;
					}

					text {
						position: relative;
						padding-right: 30rpx;
					}

					// text::after {
					// 	position: absolute;
					// 	right: 0rpx;
					// 	top: 17rpx;
					// 	content: '';
					// 	border: 1rpx solid rgba(57, 72, 107, 1);
					// 	border-width: 0 3rpx 3rpx 0;
					// 	padding: 6rpx;
					// 	transform: rotate(-45deg);
					// 	-webkit-transform: rotate(-45deg);

					// }
				}

				.right {
					font-size: 32rpx;
					display: flex;
					align-items: center;

					image {
						width: 27rpx;
						height: 33rpx;
						margin-right: 20rpx;
					}

				}
			}
			.content{
				border-bottom: 16rpx rgba(102,102,102,0.06) solid;
				.coupon{
					width: 100%;
					display: flex;
					box-sizing: border-box;
					padding: 0rpx 28rpx;
					align-items: center;
					height:100rpx;
					background:rgba(255,188,0,0.1);
					font-size: 28rpx;
					color: #666666;
					text{
						color: #EB5938;
					}
				}
				.contop{
					display: flex;
					align-items: center;
					box-sizing: border-box;
				    padding-left: 30rpx;
					height: 100rpx;
					border-bottom: 1rpx #EBECF0 solid;
					image {
						width:40rpx;
						height:35rpx;
						margin-left: 50rpx;
					}
									
					.sel {
						background-image: url(https://hdsq.aoorange.cn/attachment/xcx/icon/xuanzhong.png);
						background-repeat: no-repeat;
						width: 40rpx;
						height: 40rpx;
						background-size: 100%;
					}
									
					.nosel {
						width: 36rpx;
						height: 36rpx;
						border: 1rpx solid #999999;
						border-radius: 50%;
					}
					text{
						color: #333333;
						font-size: 28rpx;
						margin-left: 10rpx;
					}
				}
				.cont:last-child{
					border: none;
				}
				.cont {
					width: 100%;
					display: flex;
					align-items: center;
					box-sizing: border-box;
					padding: 40rpx 30rpx;
					border-bottom: 1rpx #EBECF0 solid;			
					.left {
						display: flex;
						align-items: center;
				
						image {
							width: 170rpx;
							height: 170rpx;
							margin-left: 50rpx;
						}
				
						.sel {
							background-image: url(https://hdsq.aoorange.cn/attachment/xcx/icon/xuanzhong.png);
							background-repeat: no-repeat;
							width: 40rpx;
							height: 40rpx;
							background-size: 100%;
						}
				
						.nosel {
							width: 36rpx;
							height: 36rpx;
							border: 1rpx solid #999999;
							border-radius: 50%;
						}
					}
				
					.right {
						width: 440rpx;
						height: 100%;
						position: relative;
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						margin-left: 20rpx;
				
						// .uni-numbox {
						// 	display: flex;
						// 	align-items: center;
						// 	position: absolute;
						// 	height: 60rpx;
						// 	background: rgba(255, 255, 255, 1);
						// 	border: 1rpx solid rgba(60, 72, 104, 0.1);
						// 	border-radius: 32rpx;
						// 	overflow: hidden;
						// 	bottom: 0rpx;
						// 	right: 0rpx;
						// }
						
						.uni-numbox {
							display: flex;  
							flex-direction: row;  
							align-items: center;
							position: absolute;
							justify-content: flex-start;  
							background: rgba(255, 255, 255, 1);
							border: 1rpx solid #CCCCCC;
							border-radius: 32rpx;
							height: 60rpx;  
							overflow: hidden;
							bottom: 0rpx;
							right: 0rpx;
						}  
									
						.uni-numbox-minus,  
						.uni-numbox-plus {  
							margin: 0;  
							background-color: #FFFFFF;  
							width: 70rpx;  
							height: 100%;  
							line-height: 60rpx;  
							text-align: center;  
							color: #555555;  
						}  
									
						.uni-numbox-minus {  
							// border: 1rpx solid #cccccc;  
							border-right: none;  
							border-top-left-radius: 32rpx;  
							border-bottom-left-radius: 32rpx;  
						}  
									
						.uni-numbox-plus {  
							// border: 1rpx solid #cccccc;  
							border-left: none;  
							border-top-right-radius: 32rpx;  
							border-bottom-right-radius: 32rpx;  
						}  
									
						.uni-numbox-value {  
							border: 1rpx solid rgba(60,72,104,0.06);
							background-color: #ffffff;  
							width: 80rpx;  
							height: 100%;  
							text-align: center;  
						}  
									
						.uni-numbox-disabled {  
							color: #c0c0c0;  
						} 
				
						.right-p {
							font-size: 32rpx;
							font-weight: bold;
							overflow: hidden;
							word-break: break-all;
							text-overflow: ellipsis; 
							display: -webkit-box; 
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
						}
				
						text:nth-child(2) {
							font-size: 24rpx;
							color: #EB5938;
							font-weight: bold;
						}
						.price{
							color: #FF0000;
							font-size: 24rpx;
						}
						.oneline {
							font-size: 20rpx;
							color: #999999;
							width: 200rpx;
							text-decoration: line-through;
							
						}
                        
                        .state{
                            padding: 5rpx 8rpx;
                            text-align: center;
                            color: #FFFFFF;
                            font-size: 32rpx;
                            border-radius:2rpx;
                            margin-right: 10rpx;
                        }
					}
				}
			}
			

			.bottom {
				// padding-bottom: env(safe-area-inset-bottom);
				border-top: 1rpx #EBECF0 solid;
				position: fixed;
				bottom: 0rpx;
				background: #FFFFFF;
				box-sizing: border-box;
				padding-left: 30rpx;
				display: flex;
				align-items: center;
				width: 100%;
				height: 100rpx;
				box-shadow: 0px 1rpx 0px 0px rgba(235, 236, 240, 1);
				justify-content: space-between;

				.left {
					display: flex;
					align-items: center;
					font-size: 28rpx;

					.sel {
						background-image: url(https://hdsq.aoorange.cn/attachment/xcx/icon/xuanzhong.png);
						background-repeat: no-repeat;
						width: 40rpx;
						height: 40rpx;
						background-size: 100%;
						margin-right: 20rpx;
					}

					.nosel {
						width: 36rpx;
						height: 36rpx;
						border: 1rpx solid #999999;
						border-radius: 50%;
						margin-right: 20rpx;
					}
				}

				.right {
					display: flex;
					height: 100%;

					.del {
						width: 240rpx;
						height: 72rpx;
						background: rgba(255,188,0,0.1);;
						color: #FFBC00;
						border-radius: 36rpx;
						text-align: center;
						margin-top: 17rpx;
						margin-right: 70rpx;
						text-align: center;
						line-height: 72rpx;
						font-size: 28rpx;
					}

					.text {
						display: flex;
						justify-content: center;
						align-items: flex-end;
						padding-right: 15rpx;
						flex-direction: column;

						.all {
							font-size: 20rpx;
							color: rgba(60, 72, 104, 0.5);

							text:last-child {
								margin-left: 10rpx;
								font-size: 28rpx;
								font-weight: bold;
								color: #FF5F60;
							}
						}

						.freight {
							font-size: 20rpx;
							color: rgba(60, 72, 104, 0.5);
						}
					}

					.pay {
						width: 240rpx;
						height: 100%;
						background: rgba(235, 89, 56, 1);
						text-align: center;
						line-height: 100rpx;
						font-size: 28rpx;
						color: #FFFFFF;
						font-weight: bold;
					}
				}
			}

		}
	}
</style>
